L.ZoomControlledFeatureGroup = L.FeatureGroup.extend({
	initialize: function (layers, minZoom, maxZoom, options) {
		L.FeatureGroup.prototype.initialize.call(this, layers, options)
		this.minZoom = minZoom
		this.maxZoom = maxZoom
		this._tempLayers = []
		this._isInRange = false // 新增标志
		this._updateLayer = this._updateLayer.bind(this)
	},
	_throttle: function (func, limit) {
		let lastFunc
		let lastRan
		return function (...args) {
			const context = this
			if (!lastRan) {
				func.apply(context, args)
				lastRan = Date.now()
			} else {
				clearTimeout(lastFunc)
				lastFunc = setTimeout(() => {
					if (Date.now() - lastRan >= limit) {
						func.apply(context, args)
						lastRan = Date.now()
					}
				}, limit - (Date.now() - lastRan))
			}
		}
	},

	onAdd: function (map) {
		L.FeatureGroup.prototype.onAdd.call(this, map)
		const isInRange = map.getZoom() >= this.minZoom && map.getZoom() <= this.maxZoom
		if (!isInRange) {
			this._isInRange = true
		}
		this._checkZoom(map.getZoom()) // 初始检查

		map.on('zoomend', () => {
			this._checkZoom(map.getZoom())
		})
	},
	_checkZoom: function (currentZoom) {
		console.info(`currentZoom:`, currentZoom)
		const isInRange = currentZoom >= this.minZoom && currentZoom <= this.maxZoom
		console.info(`isInRange:`, isInRange)
		if (isInRange && !this._isInRange) {
			this._updateLayer() // 进入范围时触发
			this._isInRange = true
		} else if (!isInRange && this._isInRange) {
			this._updateLayer() // 离开范围时触发
			this._isInRange = false
		}
	},
	addLayer: function (layerOrkey) {
		let layer = layerOrkey
		L.FeatureGroup.prototype.addLayer.call(this, layer)

		this._tempLayers.push(layer) // 缓存加入的图层，用于图层显隐藏
	},

	onRemove: function (map) {
		L.FeatureGroup.prototype.onRemove.call(this, map)
		map.off('zoomend', this._updateLayer)
	},

	_updateLayer: function () {
		const currentZoom = this._map.getZoom()
		console.info(`currentZoom:`, this, currentZoom)
		if (currentZoom < this.minZoom || currentZoom > this.maxZoom) {
			L.FeatureGroup.prototype.clearLayers.call(this)
		} else {
			if (Object.keys(this._layers).length == 0) {
				this._tempLayers.forEach((la) => {
					L.FeatureGroup.prototype.addLayer.call(this, la)
				})
			}
			//
		}
	}
})

L.zoomControlledFeatureGroup = (layers, minZoom, maxZoom, options) => {
	return new L.ZoomControlledFeatureGroup(layers, minZoom, maxZoom, options)
}
